# coding: utf-8

import os
import time
import logging
from logging.handlers import TimedRotatingFileHandler


class Handler(TimedRotatingFileHandler):
    """
    create by ld_wu 2018-06-15
    修复多进程log丢失问题
    """

    def doRollover(self):
        """
        do a rollover; in this case, a date/time stamp is appended to the filename
        when the rollover happens.  However, you want the file to be named for the
        start of the interval, not the current time.  If there is a backup count,
        then we have to get a list of matching filenames, sort them and remove
        the one with the oldest suffix.
        """
        if self.stream:
            self.stream.close()
            self.stream = None
        # get the time that this sequence started at and make it a time_tuple
        current_time = int(time.time())
        dst_now = time.localtime(current_time)[-1]
        t = self.rolloverAt - self.interval
        if self.utc:
            time_tuple = time.gmtime(t)
        else:
            time_tuple = time.localtime(t)
            dst_then = time_tuple[-1]
            if dst_now != dst_then:
                if dst_now:
                    addend = 3600
                else:
                    addend = -3600
                time_tuple = time.localtime(t + addend)
        dfn = self.rotation_filename(self.baseFilename + "." +
                                     time.strftime(self.suffix, time_tuple))
        # start
        # if os.path.exists(dfn):
        #     os.remove(dfn)
        # self.rotate(self.baseFilename, dfn)
        if not os.path.exists(dfn):
            self.rotate(self.baseFilename, dfn)
        # end

        if self.backupCount > 0:
            for s in self.getFilesToDelete():
                os.remove(s)
        if not self.delay:
            self.stream = self._open()
        new_rollover_at = self.computeRollover(current_time)
        while new_rollover_at <= current_time:
            new_rollover_at = new_rollover_at + self.interval
        # If DST changes and midnight or weekly rollover, adjust for this.
        if (self.when == 'MIDNIGHT' or self.when.startswith(
                'W')) and not self.utc:
            dst_at_rollover = time.localtime(new_rollover_at)[-1]
            if dst_now != dst_at_rollover:
                if not dst_now:
                    # DST kicks in before next rollover,
                    # so we need to deduct an hour
                    addend = -3600
                else:
                    # DST bows out before next rollover,
                    # so we need to add an hour
                    addend = 3600
                new_rollover_at += addend
        self.rolloverAt = new_rollover_at


logger = logging.getLogger(__name__)

# 指定logger输出格式
formatter = logging.Formatter(
    '[%(asctime)s %(filename)s-%(funcName)s-%(lineno)d] %(message)s'
)

log_file = os.path.join(
    os.environ.get('logging_file') or '/var/log/python', 'mq.log'
)
# 文件日志
file_handler = Handler(
    log_file,
    when='MIDNIGHT',
    backupCount=30,
    encoding='utf-8'
)
file_handler.setFormatter(formatter)  # 可以通过setFormatter指定输出格式

# 为logger添加的日志处理器
logger.addHandler(file_handler)
logger.setLevel(logging.DEBUG)


Log = logger


if __name__ == '__main__':
    Log.info('test')


